package cn.xfdzx.android.apps.shop.wxapi;


import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.weixin.view.WXCallbackActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.apps.MyApp;
import cn.xfdzx.android.apps.shop.evenbus.WeChatCodeEvent;

public class WXEntryActivity extends WXCallbackActivity implements IWXAPIEventHandler {
//    @Override
//    public void onReq(BaseReq baseReq) {
//
//    }
//
//    @Override
//    public void onResp(BaseResp baseResp) {
//
//    }

    public int WX_LOGIN = 1;

    private IWXAPI iwxapi;

    private SendAuth.Resp resp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getSupportActionBar().hide();
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        //iwxapi = WXAPIFactory.createWXAPI(this, Constants.WX_APPID, true);
        //接收到分享以及登录的intent传递handleIntent方法，处理结果
        MyApp.mWxApi.handleIntent(getIntent(), this);
        Log.e("savedInstanceState","savedInstanceState");

    }


    @Override
    public void onReq(BaseReq baseReq) {
        Log.e("baseResp","baseReq==");
    }


    /**
     * 登录微信
     *
     * @param api 微信服务api
     */
    public static void loginWeixin(Context context, IWXAPI api) {
        // 判断是否安装了微信客户端
        if (!api.isWXAppInstalled()) {
            Toast.makeText(context.getApplicationContext(), "您还未安装微信客户端！", Toast.LENGTH_SHORT).show();
            return;
        }
        // 发送授权登录信息，来获取code
        SendAuth.Req req = new SendAuth.Req();
        // 应用的作用域，获取个人信息
        req.scope = "snsapi_userinfo";
        /**
         * 用于保持请求和回调的状态，授权请求后原样带回给第三方
         * 为了防止csrf攻击（跨站请求伪造攻击），后期改为随机数加session来校验
         */
        req.state = "app_wechat";
        api.sendReq(req);

    }

    //请求回调结果处理
    @Override
    public void onResp(BaseResp baseResp) {
        Log.e("baseResp",baseResp.openId+"===");
        //微信登录为getType为1，分享为0
        if (baseResp.getType() == WX_LOGIN) {
            resp = (SendAuth.Resp) baseResp;

            switch (resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    String code = String.valueOf(resp.code);
                    Log.e("baseResp",code+"==code=");
                    //  boolean auth = UMShareAPI.get(this).isAuthorize(this, SHARE_MEDIA.WEIXIN);

                    EventBus.getDefault().post(new WeChatCodeEvent(code));
                    // Log.e("TAG", "======--------------="+auth);

                    //获取用户信息
                  //  getAccessToken(code);
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED://用户拒绝授权
                    Toast.makeText(WXEntryActivity.this, "用户拒绝授权", Toast.LENGTH_LONG).show();
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
                    Toast.makeText(WXEntryActivity.this, "用户取消登录", Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        } else {
            //分享成功回调
            System.out.println("------------分享回调------------");
            switch (baseResp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    //分享成功
                    Toast.makeText(WXEntryActivity.this, "分享成功", Toast.LENGTH_LONG).show();
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    //分享取消
                    Toast.makeText(WXEntryActivity.this, "分享取消", Toast.LENGTH_LONG).show();
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    //分享拒绝
                    Toast.makeText(WXEntryActivity.this, "分享拒绝", Toast.LENGTH_LONG).show();
                    break;
            }
        }
        finish();
    }

//    private void getAccessToken(String code) {
//        //获取授权
//        String http = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constant.APP_ID + "&secret=" + Constant.API_KEY + "&code=" + code + "&grant_type=authorization_code";
//        OkHttpUtils.ResultCallback<String> resultCallback = new OkHttpUtils.ResultCallback<String>() {
//            @Override
//            public void onSuccess(String response) {
//                String access = null;
//                String openId = null;
//                try {
//                    JSONObject jsonObject = new JSONObject(response);
//                    access = jsonObject.getString("access_token");
//                    openId = jsonObject.getString("openid");
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//                //获取个人信息
//                String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openId + "";
//                OkHttpUtils.ResultCallback<WeChatInfo> resultCallback = new OkHttpUtils.ResultCallback<WeChatInfo>() {
//                    @Override
//                    public void onSuccess(WeChatInfo response) {
//                        response.setErrCode(resp.errCode);
//                        SPUtils.put(WXEntryActivity.this, response.getOpenid(), "");
//                        Log.e("WEIXIN", response.toString());
////                        Toast.makeText(WXEntryActivity.this, new Gson().toJson(response), Toast.LENGTH_LONG).show();
//                        finish();
//                    }
//
//                    @Override
//                    public void onFailure(Exception e) {
//                        Toast.makeText(WXEntryActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
//                    }
//                };
//                OkHttpUtils.get(getUserInfo, resultCallback);
//            }
//
//            @Override
//            public void onFailure(Exception e) {
//                Toast.makeText(WXEntryActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
//            }
//        };
//        OkHttpUtils.get(http, resultCallback);
//    }
}
